/**
 * 粒子系统 - 管理粒子效果
 */
import { System, World, Entity } from '../ecs';
import { Transform, Renderer, Particle } from '../components';

export class ParticleSystem implements System {
  priority = 60;

  update(deltaTime: number, world: World): void {
    this.updateParticles(world, deltaTime);
  }

  private updateParticles(world: World, deltaTime: number): void {
    const particles = Array.from(world.entities).filter(e => 
      e.hasComponent('particle') && e.hasComponent('transform') && e.hasComponent('renderer')
    );
    
    for (const particle of particles) {
      const particleComponent = particle.getComponent<Particle>('particle')!;
      const transform = particle.getComponent<Transform>('transform')!;
      const renderer = particle.getComponent<Renderer>('renderer')!;
      
      // 更新粒子生命周期
      particleComponent.lifeTime += deltaTime;
      
      // 如果粒子生命周期结束，删除它
      if (particleComponent.lifeTime >= particleComponent.maxLifeTime) {
        world.removeEntity(particle);
        continue;
      }
      
      // 计算生命周期进度 (0-1)
      const progress = particleComponent.lifeTime / particleComponent.maxLifeTime;
      
      // 应用重力
      transform.velocityY += particleComponent.gravity * deltaTime;
      
      // 插值计算当前大小和透明度
      const currentSize = this.lerp(
        particleComponent.startSize, 
        particleComponent.endSize, 
        progress
      );
      const currentAlpha = this.lerp(
        particleComponent.startAlpha, 
        particleComponent.endAlpha, 
        progress
      );
      
      // 更新渲染属性
      renderer.radius = currentSize;
      
      // 更新颜色透明度（假设颜色格式为 #rrggbb）
      const baseColor = renderer.color.replace('#', '');
      const r = parseInt(baseColor.substr(0, 2), 16);
      const g = parseInt(baseColor.substr(2, 2), 16);
      const b = parseInt(baseColor.substr(4, 2), 16);
      
      renderer.color = `rgba(${r}, ${g}, ${b}, ${currentAlpha})`;
    }
  }

  /**
   * 创建爆炸粒子效果
   */
  createExplosion(world: World, x: number, y: number, color = '#ffaa00', particleCount = 8): void {
    for (let i = 0; i < particleCount; i++) {
      const angle = (Math.PI * 2 * i) / particleCount;
      const speed = 100 + Math.random() * 100;
      const velocityX = Math.cos(angle) * speed;
      const velocityY = Math.sin(angle) * speed;
      
      const particle = new Entity()
        .addComponent('transform', {
          x: x + (Math.random() - 0.5) * 10,
          y: y + (Math.random() - 0.5) * 10,
          rotation: 0,
          velocityX,
          velocityY
        })
        .addComponent('renderer', {
          color,
          radius: 6,
          shape: 'circle' as const
        })
        .addComponent('particle', {
          lifeTime: 0,
          maxLifeTime: 0.8 + Math.random() * 0.4,
          startSize: 6,
          endSize: 0,
          startAlpha: 1,
          endAlpha: 0,
          gravity: 50
        });
      
      world.addEntity(particle);
    }
  }

  /**
   * 创建推进器尾焰效果
   */
  createThrusterTrail(world: World, x: number, y: number): void {
    const particle = new Entity()
      .addComponent('transform', {
        x: x + (Math.random() - 0.5) * 8,
        y: y + 15,
        rotation: 0,
        velocityX: (Math.random() - 0.5) * 20,
        velocityY: 50 + Math.random() * 30
      })
      .addComponent('renderer', {
        color: '#00aaff',
        radius: 3,
        shape: 'circle' as const
      })
      .addComponent('particle', {
        lifeTime: 0,
        maxLifeTime: 0.3,
        startSize: 3,
        endSize: 0,
        startAlpha: 0.8,
        endAlpha: 0,
        gravity: 0
      });
    
    world.addEntity(particle);
  }

  /**
   * 创建击中效果
   */
  createHitEffect(world: World, x: number, y: number, color = '#ffffff'): void {
    for (let i = 0; i < 4; i++) {
      const angle = Math.random() * Math.PI * 2;
      const speed = 50 + Math.random() * 50;
      const velocityX = Math.cos(angle) * speed;
      const velocityY = Math.sin(angle) * speed;
      
      const particle = new Entity()
        .addComponent('transform', {
          x,
          y,
          rotation: 0,
          velocityX,
          velocityY
        })
        .addComponent('renderer', {
          color,
          radius: 2,
          shape: 'circle' as const
        })
        .addComponent('particle', {
          lifeTime: 0,
          maxLifeTime: 0.2,
          startSize: 2,
          endSize: 0,
          startAlpha: 1,
          endAlpha: 0,
          gravity: 0
        });
      
      world.addEntity(particle);
    }
  }

  private lerp(start: number, end: number, progress: number): number {
    return start + (end - start) * progress;
  }
}